package jrain.fw.dao.common.format;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import jrain.fw.core.dao.ColumnFormat;
import jrain.fw.core.dao.ColumnFormatHandler;
import jrain.fw.core.dao.ColumnFormatProvider;
import jrain.fw.core.log.Logger;
import jrain.fw.core.log.LoggerFactory;
import jrain.fw.core.service.DestroyService;
import jrain.fw.core.service.InitService;
import jrain.fw.core.service.Service;
import jrain.fw.core.service.ServiceCfg;
import jrain.fw.core.service.ServiceConst;
import jrain.fw.core.utils.FwUtils;
import jrain.utils.cls.ClassUtils;
import jrain.utils.collection.CollectionUtils;
import jrain.utils.collection.RMap;
import jrain.utils.exception.ServiceException;
import jrain.utils.lang.StringUtils;

/**
 * <pre>
 * 作者：489088214@qq.com 
 * 描述：列数据格式化
 * </pre>
 */
@Service(group = ServiceConst.S_DAO_COLUMN_FORMAT_PROVIDER, module = ServiceConst.M_DAO)
public class DefaultFormatProvider implements ColumnFormatProvider, InitService, DestroyService {

	private static final Logger log = LoggerFactory.getLogger("dao-format-register");
	private static final Map<String, ColumnFormatHandler> register = new HashMap<>();
	private final String pkgs;

	public DefaultFormatProvider() {
		RMap<String, Object> cfg = FwUtils.getFwCfg();
		pkgs = StringUtils.trimNull(cfg.get(ServiceCfg.daoColumnFormatScan.getName()),
				ServiceCfg.daoColumnFormatScan.getValue());
	}

	public void init() {
		try {
			log.info("dao format begin!");
			List<String> pkgList = CollectionUtils.valueOfList(pkgs);
			log.info("dao format scan pkgs {}", pkgs);
			for (String string : pkgList) {
				Set<Class<?>> list = ClassUtils.getClasses(string);
				for (Class<?> claz : list) {
					ColumnFormat service = claz.getAnnotation(ColumnFormat.class);
					if (service != null) {
						Object obj = claz.newInstance();
						if (obj instanceof ColumnFormatHandler) {
							String key = service.name();
							log.info("dao format scan find name:{} class:{}", key, claz.getName());
							register.put(key, (ColumnFormatHandler) obj);
						} else {
							log.warn("dao format find {} not implements ColumnFormatHandler", claz.getName());
						}

					}
				}
			}
			log.info("dao format end!");
		} catch (Exception e) {
			String msg = "dao format error!";
			log.error(msg, e);
			throw new ServiceException(msg, e);
		}
	}

	@Override
	public ColumnFormatHandler getHandler(String format) {
		return register.get(format);
	}

	@Override
	public void destroy() {
		register.clear();
	}

}
